package com.cbtx.tablet.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.cbtx.tablet.App
import com.cbtx.tablet.bean.Report
import com.cbtx.tablet.constant.HttpConstant
import com.cbtx.tablet.device.MachineFactory
import com.cbtx.tablet.net.HttpResponse
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 10:58 AM
 * desc   :
 */
abstract class AbsBaseActivity : FragmentActivity() {

    companion object {
        const val REQUEST_OVERLAY = 0x001
        const val REQUEST_WIFI_SET = 0x002
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        //全屏显示
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        setContentView(layoutId())

        hideBottomButton()

        initView(savedInstanceState)

        initData(savedInstanceState)

    }

    private fun hideBottomButton() {
        val window = window
        val params = window.attributes
        params.systemUiVisibility =
            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE
        window.attributes = params
    }

    /**
     * 提供视图布局Id, 如果 [.initView] 返回 0, 框架则不会调用 [Activity.setContentView]
     * @return
     */
    @LayoutRes
    abstract fun layoutId(): Int

    /**
     * 初始化View
     *
     * @param savedInstanceState
     * @return
     */
    abstract fun initView(savedInstanceState: Bundle?)

    /**
     * 初始化数据
     *
     * @param savedInstanceState
     */
    abstract fun initData(savedInstanceState: Bundle?)


    fun toNetSet() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
            startActivityForResult(panelIntent, REQUEST_WIFI_SET)
        } else {
            val intent = Intent()
            intent.action = "android.net.wifi.PICK_WIFI_NETWORK"
            intent.putExtra(":settings:show_fragment_as_subsetting", true)
            startActivityForResult(intent, REQUEST_WIFI_SET)
        }
    }

    fun report() {

        var map = mutableMapOf<String, Any?>()
        var iMachine = MachineFactory.getAutoCreate(this)
        map["intranetIP"] = NetworkUtils.getIPAddress(true)
        map["imsi"] = iMachine.getIMSI()
        map["totalStorage"] = iMachine.getTotalExternalMemorySize()
        map["availableStorage"] = iMachine.getAvailableExternalMemorySize()
        map["temperature"] = iMachine.getTemperature()
        map["humidity"] = iMachine.getHumidity()
        map["lastRebootTime"] = App.bootTime
        map["packageName"] = packageName(App.instance)

        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .report(map)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {
                    reportSuccess(it)
                }
            )
    }

    fun packageName(context: Context): String {
        val manager = context.packageManager
        var name = ""
        try {
            val info = manager.getPackageInfo(context.packageName, 0)
            name = info.applicationInfo.packageName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return name
    }

    /**
     * 上报数据时，设备认证成功
     */
    open fun reportSuccess(report: HttpResponse<Report>?){

    }
}